<?php
/**
 * 产品分表
 * 分表规则：表名+公司id+语言名称
 * Created by PhpStorm.
 * User: pc
 * Date: 2018/12/14
 * Time: 17:07
 */

namespace app\admin\model;

use think\Db;
use think\Model;
use app\Config;
use PDO;

class Product extends Model
{
    public $pdo = '';
    public $dbName = '';

    public function __construct()
    {
        $dbms = $this->getConfig('type');     //数据库类型
        $host = $this->getConfig('hostname'); //数据库主机名
        $this->dbName = $this->getConfig('database');    //使用的数据库
        $this->pdo = new PDO("$dbms:host=$host;dbname=$this->dbName", $this->getConfig('username'), $this->getConfig('password'));
    }

    /**
     * 检测数据表是否存在
     * @param string $table
     * @return bool
     */
    public function checkTableExist($table = '')
    {
        $tableName = $table ? $table : self::getTable();
        $sql = sprintf("SELECT COUNT(1) FROM `INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_SCHEMA`='%s' AND `TABLE_NAME` = '%s'", $this->dbName, $this->getConfig('prefix') . $tableName);
        $result = $this->pdo->query($sql);
        if ($result === false) {//表不存在
            return false;
        }
        if (!$result->fetchColumn(0)) {
            return false;
        }
        return true;
    }

    /**
     * 复制表结构
     * @param string $table
     * @param string $newTable
     * @param string $company_id
     * @return bool
     */
    public function copyTable($table = '', $newTable = '', $company_id = '')
    {
        $table = $this->getConfig('prefix') . $table;
        $newTable = $this->getConfig('prefix') . $newTable;
        $sql = sprintf("create table %s like %s", $newTable, $table);
        $result = $this->pdo->query($sql);
        if ($result === false) {
            return false;
        }
        $sql = sprintf("alter table %s comment '%s'", $newTable, '公司-' . $company_id . "_" . $table . '分表');
        $this->pdo->query($sql);
        return true;
    }

    /**
     * 获取产品列表
     * @param array $data
     * @param string $company_id
     * @param string $where
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function productList($data = [], $company_id = 0, $where = [], $pcompany_id = '')
    {
        //产品表
        $productTbale = 'products';
        $lanid = isset($data['lanid']) ? $data['lanid'] : '';
        $newProductTable = !empty($lanid) ? $productTbale . "_" . $lanid . "_" . $company_id : $productTbale . "_" . $company_id;
        //公司分表不存在
        if ($this->checkTableExist($newProductTable) == false) {
            $this->copyTable($productTbale, $newProductTable, $company_id);
        }
        $proname = isset($data['proname']) ? $data['proname'] : '';
        $code = isset($data['code']) ? $data['code'] : '';
        $platformStr = isset($data['platformStr']) ? $data['platformStr'] : '';
        $audit = isset($data['audit']) ? $data['audit'] : '';
        $bname = isset($data['bname']) ? $data['bname'] : '';//分类
        $start = isset($data['start']) ? $data['start'] : '';
        $end = isset($data['end']) ? $data['end'] : '';
        $user_name = isset($data['user_name']) ? $data['user_name'] : '';
        $user_name = $user_name ? $user_name : ssession('username');

        !empty($code) && $where['skucode'] = ['like', '%' . $code . '%'];
        !empty($proname) && $where['proname'] = ['like', '%' . $proname . '%'];
        !empty($platformStr) && $where['platform'] = $platformStr;
        !empty($bname) && $where['bname'] = $bname;
        !empty($audit) && $where['audit'] = $audit;
        !empty($start) && $where['ndate'] = ['>', $start];
        !empty($end) && $where['ndate'] = ['<', $end];

        //判断是否是管理员
        !checkAdministrator() && $where['user_name'] = $user_name;

        $list_rows = iget('list_rows') ? iget('list_rows') : 20;
        $dataArr = Db::name($newProductTable)
            ->where($where)
            ->order('id desc')
            ->paginate($list_rows, false, ['query' =>
                [
                    'proname' => $proname,
                    'code' => $code,
                    'platformStr' => $platformStr,
                    'lanid' => $lanid,
                    'bname' => $bname,
                    'company_id' => $pcompany_id,
                    'user_name' => $user_name,
                    'audit' => $audit,
                    'start' => $start,
                    'end' => $end,
                    'bcate_id' => isset($data['bcate_id']) ? $data['bcate_id'] : '',
                    'list_rows' => $list_rows
                ]]);
        return $dataArr;
    }

    /**
     * guid 获取图片信息
     * @param $where
     * @param string $company_id
     * @return array|false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getImgInfo($where, $company_id = '')
    {
        //产品图表
        $productImgTbale = "img_" . $company_id;

        if ($this->checkTableExist($productImgTbale) == false) {
            return [];
        }

        //资源表
        $resourceTbale = "resource_" . $company_id;
        //公司分表不存在
        if ($this->checkTableExist($resourceTbale) == false) {
            return [];
        }

        //获取图片关联数据
        $sql = Db::table($this->getConfig('prefix') . $productImgTbale)
            ->where($where)
            ->order('px asc')
//            ->group('guid')
            ->buildSql();


        $imgInfo = Db::table($sql . 'a')->group('a.guid')->select();
        if (!checkArr($imgInfo)) {
            return [];
        }

        //获取资源id
        $resource_ids = array_column($imgInfo, 'resource_id');
        $resource = Db::name($resourceTbale)
            ->where(['id' => ['in', join(',', $resource_ids)]])
            ->select();
        $resources = arrayCombine($resource, 'id');
        foreach ($imgInfo as $key => $value) {
            $imgInfo[$key]['imgpath'] = isset($resources[$value['resource_id']]['path']) ? $resources[$value['resource_id']]['path'] : '';
        }
        return $imgInfo;
    }

    /**
     * 获取资源文件id
     * @param $where
     * @param $company_id
     * @return array|false|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getResource($where, $company_id)
    {
        //资源表
        $resourceTbale = "resource";
        $newResourceTbale = $resourceTbale . "_" . $company_id;
        //公司分表不存在
        if ($this->checkTableExist($newResourceTbale) == false) {
            $this->copyTable($resourceTbale, $newResourceTbale, $company_id);
            return [];
        }
        return DB::name($newResourceTbale)->where($where)->find();
    }

    /**
     * 检测产品SKU获取GUID是否重复
     * 不存在  ['state'=>true]
     * 存在   ['state'=>false,'msg'=>'错误提示']
     * @param array $data
     * @param string $company_id
     * @return array
     * @throws \think\Exception
     */
    public function productCheck($data = [], $company_id = '')
    {
        //产品表
        $productTbale = 'products';
        $newProductTable = $data['lang'] ? $productTbale . "_" . $data['lang'] . "_" . $company_id : $productTbale . "_" . $company_id;
        //公司分表不存在
        if ($this->checkTableExist($newProductTable) == false) {
            $this->copyTable($productTbale, $newProductTable, $company_id);
            return ['state' => true];
        }

//        $where = '';
//        $where .= $data['skucode'] ? "skucode = '" . $data['skucode'] . "'" : "";
//        $where .= $data['guid'] ? $where ? " OR guid = '" . $data['guid'] . "'" : " guid = '" . $data['guid'] . "'" : "";


        $where['skucode'] = $data['skucode'] ? $data['skucode'] : [];
        $orwhere['guid'] = $data['guid'] ? $data['guid'] : [];
        $num = Db::name($newProductTable)->where($where)->whereOr($orwhere)->count();
        return $num == 0 ? ['state' => true] : ['state' => false, 'msg' => 'SKU已存在，请重新输入'];
    }

    /**
     * 批量转移产品分类
     * @param array $data
     * @param string $company_id
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function massTransfer($data = [], $company_id = '')
    {
        $company_id = empty($company_id) ? isession('company_id') : $company_id;
        $productTbale = 'products';
        $newProductTable = $data['lang'] ? $productTbale . "_" . $data['lang'] . "_" . $company_id : $productTbale . "_" . $company_id;
        if ($this->checkTableExist($newProductTable) == false) {
            $this->copyTable($productTbale, $newProductTable, $company_id);
        }
        $where['guid'] = ['in',$data['guid']];
        $where['user_name'] = ssession('username');
        DB::name($newProductTable)->where($where)->update(['bname' => $data['bname'], 'platform' => $data['platform']]);
        return true;
    }

    /**
     * 新增产品
     * @param array $data
     * @param string $company_id
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function productAdd($data = [], $company_id = '')
    {
        //计算上传图片所占空间大小
        $num = (isset($data['ppsize']) && checkArr($data['ppsize'])) ? array_sum($data['ppsize']) : 0;
        if (isset($data["imgid"]) && checkArr($data["imgid"])) {
            foreach ($data["imgid"] as $key => $value) {
                (isset($data["bbsize" . $value]) && checkArr($data["bbsize" . $value])) && $num += array_sum($data["bbsize" . $value]);
            }
        }
        //获取公司信息
        if (isession('type') == 2) {
            $company = DB::name('company')->where('id', $company_id)->find();
            if (!checkDiskSpace($company, $num)) {
                return false;
            }
        }

        //产品表
        $productTbale = 'products';
        $newProductTable = $data['lang'] ? $productTbale . "_" . $data['lang'] . "_" . $company_id : $productTbale . "_" . $company_id;

        //产品图表
        $productImgTbale = 'img';
        $newProductImgTbale = $productImgTbale . "_" . $company_id;
        //属性表
        $propertyTbale = 'shuxing';
        $newPropertyTbale = $propertyTbale . "_" . $company_id;
        //资源表
        $resourceTbale = "resource";
        $newResourceTbale = $resourceTbale . "_" . $company_id;

        //公司分表不存在
        if ($this->checkTableExist($newProductTable) == false) {
            $this->copyTable($productTbale, $newProductTable, $company_id);
        }
        if ($this->checkTableExist($newProductImgTbale) == false) {
            $this->copyTable($productImgTbale, $newProductImgTbale, $company_id);
        }
        if ($this->checkTableExist($newPropertyTbale) == false) {
            $this->copyTable($propertyTbale, $newPropertyTbale, $company_id);
        }
        if ($this->checkTableExist($newResourceTbale) == false) {
            $this->copyTable($resourceTbale, $newResourceTbale, $company_id);
        }

        //获取分类及平台
        $arr = explode('--', $data["bname"]);
        $product['guid'] = $data["guid"];
        $product['proname'] = transitionbr($data["proname"]);
        $product['title'] = transitionbr($data["proname"]);
        $product['tmd5'] = md5($product['proname']);
        $product['skucode'] = $data["skucode"];
        $product['price'] = $data["price"];
        $product['saleprice'] = $data["saleprice"];
        $product['coin'] = $data["coin"];
        $product['code'] = $data["code"];
        $product['carriage'] = $data["carriage"];
        $product['cost'] = $data["cost"];
        $product['kucun'] = $data["kucun"];
        $product['weight'] = $data["weight"];
        $product['fromurl'] = isset($data["fromurl"]) ? $data["fromurl"] : '';
        $product['btname'] = $data["bttname"];
        $product['sketch'] = transitionbr($data["sketch"]);
        $product['source'] = 2;
        $product['audit'] = 1;
        $product['keywords'] = transitionbr($data["keywords"]);
        $product['content'] = transitionbr($data["content"]);
        $product['bcate_id'] = $data['bcate_id'];
        $product['bname'] = $arr[0];
        $product['platform'] = $arr[1];
        $product['user_name'] = ssession('username');
        $product['ndate'] = date("Y-m-d", time());
        $product['timestamp'] = time();
        $product['brand'] = trim($data['brand']);
        $product['origin'] = trim($data['origin']);
        $product['facturer'] = trim($data['facturer']);
        $product['number'] = trim($data['number']);
        $product['department'] = trim($data['department']);
        $product['material'] = trim($data['material']);
        $product['metal'] = trim($data['metal']);
        $product['gem'] = trim($data['gem']);
        $product['package'] = trim($data['package']);
        $product['hscode'] = trim($data['hscode']);
        $product['english'] = trim($data['english']);
        $product['chinese'] = trim($data['chinese']);
        
        $rwhere['tmd5'] = $product['tmd5'];
        $product['repeat'] = $this->repeateProduct($rwhere, $newProductTable);
        //添加产品信息
        Db::name($newProductTable)->insert($product);
        $lang = $data['lang'] ? $data['lang'] : 'moren';
        //插入主图
        $proimg = isset($data["proimg"]) ? $data["proimg"] : [];
        if (checkArr($proimg)) {
            foreach ($proimg as $key => $value) {
                $resource_id = $this->insertResource($data['pname'][$key], $value, $data['psize'][$key], $data['ppostfix'][$key], $data['poriginal'][$key], $newResourceTbale);
                $productImg[] = ['resource_id' => $resource_id, 'guid' => $data["guid"], 'serial' => 0, 'px' => isset($data['px'][$key]) ? $data['px'][$key] : 0, 'lang' => $lang, 'updatetime' => date("Y-m-d H:i:s", time())];
            }
            Db::name($newProductImgTbale)->insertAll($productImg);
        }
        //插入变体
        $btname = isset($data["btname"]) ? $data["btname"] : [];
        if (checkArr($btname)) {
            $m = 0;
            foreach ($btname as $key => $value) {
                if (!empty($value) && isset($data["btsaleprice"][$key])) {
                    $m++;
                    $price = isset($data['btprice'][$key]) ? $data['btprice'][$key] : '';
                    empty($price) && $price = $data["price"];
                    $saleprice = isset($data["btsaleprice"][$key]) ? $data["btsaleprice"][$key] : '';
                    empty($saleprice) && $saleprice = $data["saleprice"];
                    $kucun = isset($data["btkucun"][$key]) ? $data["btkucun"][$key] : '';
                    $carriage = isset($data["bcarriage"][$key]) ? $data["bcarriage"][$key] : '';
                    $cost = isset($data["bcost"][$key]) ? $data["bcost"][$key] : '';
                    $property = [
                        'serial' => $m,
                        'cname' => $value,
                        'price' => $price,
                        'btname_id' => isset($data['btname_id'][$key]) ? $data['btname_id'][$key] : '',
                        'saleprice' => $saleprice,
                        'kucun' => $kucun,
                        'skucode' => $data["skucode"] . "-" . $m,
                        'carriage' => $carriage,
                        'cost' => $cost,
                        'guid' => $data["guid"],
                        'lang' => $lang
                    ];

                    Db::name($newPropertyTbale)->insert($property);
                    //插入变体图片
                    if (isset($data["imgid"][$key]) && isset($data["btimg" . $data["imgid"][$key]]) && checkArr($data["btimg" . $data["imgid"][$key]])) {
                        $btimg = $data["btimg" . $data["imgid"][$key]];
                        $propertyImg = [];
                        if (checkArr($btimg)) {
                            foreach ($btimg as $k => $v) {
                                $px = isset($data['bpx' . $data["imgid"][$key]][$k]) ? $data['bpx' . $data["imgid"][$key]][$k] : 0;
                                $resource_id = $this->insertResource($data['bname' . $data["imgid"][$key]][$k], $v, $data['bsize' . $data["imgid"][$key]][$k], $data['bpostfix' . $data["imgid"][$key]][$k], $data['boriginal' . $data["imgid"][$key]][$k], $newResourceTbale);
                                $propertyImg[] = ['resource_id' => $resource_id, 'guid' => $data["guid"], 'px' => $px, 'serial' => $m, 'lang' => $lang, 'updatetime' => date("Y-m-d H:i:s", time())];
                            }
                            count($propertyImg) > 0 && Db::name($newProductImgTbale)->insertAll($propertyImg);
                        }
                    }
                }
            }
        }

        //更改容量信息
        if (isession('type') == 2) {
            $sql = "UPDATE ean_company SET use_capacity = (use_capacity+" . $num . ") WHERE id=" . $company_id;
            $this->pdo->query($sql);
        }
        return true;
    }

    /**
     * 获取产品详细信息
     * @param string $id
     * @param string $lang
     * @param string $company_id
     * @return array|false|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function productInfo($id = '', $lang = '', $company_id = '')
    {
        //产品表
        $productTbale = 'products';
        $newProductTable = $lang ? $productTbale . "_" . $lang . "_" . $company_id : $productTbale . "_" . $company_id;
        //产品图表
        $productImgTbale = 'img';
        $newProductImgTbale = $productImgTbale . "_" . $company_id;
        //属性表
        $propertyTbale = 'shuxing';
        $newPropertyTbale = $propertyTbale . "_" . $company_id;

        //公司分表不存在
        if ($this->checkTableExist($newProductTable) == false) {
            $this->copyTable($productTbale, $newProductTable, $company_id);
            echo "当前数据不存在";
            die;
        }
        if ($this->checkTableExist($newProductImgTbale) == false) {
            $this->copyTable($productImgTbale, $newProductImgTbale, $company_id);
        }
        if ($this->checkTableExist($newPropertyTbale) == false) {
            $this->copyTable($propertyTbale, $newPropertyTbale, $company_id);
        }

        //主要数据
        $data = Db::name($newProductTable)->where('id', $id)->find();
        if (!checkArr($data)) {
            echo "当前数据不存在";
            die;
        }
        $data['imgs'] = [];

        //获取变体信息
        $where['lang'] = $lang ? $lang : 'moren';
        $where['guid'] = $data['guid'];
        $propertys = Db::name($newPropertyTbale)->where($where)->order('serial asc')->select();
        $propertys = checkArr($propertys) ? arrayCombine($propertys, 'serial') : [];

        //资源表
        $resourceTbale = "resource";
        $newResourceTbale = $resourceTbale . "_" . $company_id;
        if ($this->checkTableExist($newResourceTbale) == false) {
            $imgs = [];//图片信息
            $this->copyTable($resourceTbale, $newResourceTbale, $company_id);
        } else {
            //图片信息
            $imgs = Db::name($newProductImgTbale)->where($where)->order('px asc')->select();
        }
        if (checkArr($imgs)) {
            $resource_ids = array_unique(array_column($imgs, 'resource_id'));
            $resource = Db::name($newResourceTbale)
                ->where(['id' => ['in', join(',', $resource_ids)]])
                ->select();
            $resources = arrayCombine($resource, 'id');
            foreach ($imgs as $key => $value) {
                $resource = isset($resources[$value['resource_id']]) ? $resources[$value['resource_id']] : [];
                if ($value['serial'] == 0) {
                    checkArr($resource) && $data['imgs'][] = ['resource' => $resource, 'px' => $value['px'], 'resource_id' => $value['resource_id']];
                }
                if (checkArr($resource) && $value['serial'] > 0 && isset($propertys[$value['serial']])) {
                    $resource['px'] = $value['px'];
                    $propertys[$value['serial']]['imgs'][] = $resource;
                }
            }
        }
        $data['shuxing'] = $propertys;
        return $data;
    }

    /**
     * 提交主表编辑数据
     * @param array $data
     * @param string $company_id
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function productEdit($data = [], $company_id = '')
    {
        //计算上传图片所占空间大小
        $num = (isset($data['ppsize']) && checkArr($data['ppsize'])) ? array_sum($data['ppsize']) : 0;
        if (isset($data["imgid"]) && checkArr($data["imgid"])) {
            foreach ($data["imgid"] as $key => $value) {
                (isset($data["bbsize" . $value]) && checkArr($data["bbsize" . $value])) && $num += array_sum($data["bbsize" . $value]);
            }
        }
        //获取公司信息
        if (isession('type') == 2) {
            $company = DB::name('company')->where('id', $company_id)->find();
            if (!checkDiskSpace($company, $num)) {
                return ['status' => false, 'msg' => '空间内存不足，请提示管理员增加空间容量'];
            }
        }

        //产品表
        $productTbale = 'products';
        $newProductTable = $data['lang'] ? $productTbale . "_" . $data['lang'] . "_" . $company_id : $productTbale . "_" . $company_id;
        //产品图表
        $productImgTbale = 'img';
        $newProductImgTbale = $productImgTbale . "_" . $company_id;
        //属性表
        $propertyTbale = 'shuxing';
        $newPropertyTbale = $propertyTbale . "_" . $company_id;
        //资源表
        $resourceTbale = "resource";
        $newResourceTbale = $resourceTbale . "_" . $company_id;

        //公司分表不存在
        if ($this->checkTableExist($newProductTable) == false) {
            return ['status' => false, 'msg' => '当前数据不存在，无法修改'];
        }
        if ($this->checkTableExist($newProductImgTbale) == false) {
            $this->copyTable($productImgTbale, $newProductImgTbale, $company_id);
        }
        if ($this->checkTableExist($newPropertyTbale) == false) {
            $this->copyTable($propertyTbale, $newPropertyTbale, $company_id);
        }
        if ($this->checkTableExist($newResourceTbale) == false) {
            $this->copyTable($resourceTbale, $newResourceTbale, $company_id);
        }

        //更新产品主要信息
        $arr = explode('--', $data["bname"]);
        $product['proname'] = transitionbr($data["proname"]);
        $product['title'] = transitionbr($data["proname"]);
        $product['tmd5'] = md5($product['proname']);
        $product['skucode'] = $data["skucode"];
        $product['price'] = $data["price"];
        $product['saleprice'] = $data["saleprice"];
        $product['coin'] = $data["coin"];
        $product['code'] = $data["code"];
        $product['carriage'] = $data["carriage"];
        $product['cost'] = $data["cost"];
        $product['kucun'] = $data["kucun"];
        $product['weight'] = $data["weight"];
        $product['fromurl'] = isset($data["fromurl"]) ? $data["fromurl"] : '';
        $product['btname'] = $data["bttname"];
        $product['sketch'] = transitionbr($data["sketch"]);
        $product['keywords'] = transitionbr($data["keywords"]);
        $product['content'] = transitionbr($data["content"]);
        $product['bname'] = $arr[0];
        $product['platform'] = $arr[1];
        $product['audit'] = 1;

        $rwhere['tmd5'] = $product['tmd5'];
        $rwhere['id'] = ['neq', $data['id']];
        $product['repeat'] = $this->repeateProduct($rwhere, $newProductTable);
        $lang = $data['lang'] ? $data['lang'] : 'moren';

        $product['bcate_id'] = $data['bcate_id'];
        $product['brand'] = trim($data['brand']);
        $product['origin'] = trim($data['origin']);
        $product['facturer'] = trim($data['facturer']);
        $product['number'] = trim($data['number']);
        $product['department'] = trim($data['department']);
        $product['material'] = trim($data['material']);
        $product['metal'] = trim($data['metal']);
        $product['gem'] = trim($data['gem']);
        $product['package'] = trim($data['package']);
        $product['hscode'] = trim($data['hscode']);
        $product['english'] = trim($data['english']);
        $product['chinese'] = trim($data['chinese']);
        $product['shareguid'] = '';

        Db::name($newProductTable)
            ->where('id', $data['id'])
            ->update($product);

        //删除资源
//        if (isset($data["resource"]) && count($data["resource"]) > 0) {
//            Db::name($newResourceTbale)->where(['id' => ['in', $data["resource"]]])->delete();
//        }

        //删除图片、变体数据
        $guid = isset($data['guid']) ? $data['guid'] : create_guid();
        $where['guid'] = $guid;
        $where['lang'] = $lang;
        Db::name($newProductImgTbale)->where($where)->delete();
        Db::name($newPropertyTbale)->where($where)->delete();

        //插入主图
        $proimg = isset($data["proimg"]) ? $data["proimg"] : [];
        if (checkArr($proimg)) {
            foreach ($proimg as $key => $value) {
                $resource_id = $this->insertResource($data['pname'][$key], $value, $data['psize'][$key], $data['ppostfix'][$key], $data['poriginal'][$key], $newResourceTbale);
                $productImg[] = ['resource_id' => $resource_id, 'guid' => $guid, 'serial' => 0, 'px' => isset($data['px'][$key]) ? $data['px'][$key] : 0, 'lang' => $lang, 'updatetime' => date("Y-m-d H:i:s", time())];
            }
            Db::name($newProductImgTbale)->insertAll($productImg);
        }

        //插入变体
        $btname = isset($data["btname"]) ? $data["btname"] : [];
        if (checkArr($btname)) {
            $m = 0;
            foreach ($btname as $key => $value) {
                if (!empty($value) && isset($data["btsaleprice"][$key])) {
                    $m++;
                    $price = isset($data['btprice'][$key]) ? $data['btprice'][$key] : '';
                    empty($price) && $price = $data["price"];
                    $saleprice = isset($data["btsaleprice"][$key]) ? $data["btsaleprice"][$key] : '';
                    empty($saleprice) && $saleprice = $data["saleprice"];
                    $kucun = isset($data["btkucun"][$key]) ? $data["btkucun"][$key] : '';
                    $carriage = isset($data["bcarriage"][$key]) ? $data["bcarriage"][$key] : '';
                    $cost = isset($data["bcost"][$key]) ? $data["bcost"][$key] : '';
                    $property = [
                        'serial' => $m,
                        'cname' => $value,
                        'btname_id' => isset($data['btname_id'][$key]) ? $data['btname_id'][$key] : '',
                        'price' => $price,
                        'saleprice' => $saleprice,
                        'kucun' => $kucun,
                        'skucode' => $data["skucode"] . "-" . $m,
                        'carriage' => $carriage,
                        'cost' => $cost,
                        'guid' => $guid,
                        'lang' => $lang
                    ];

                    Db::name($newPropertyTbale)->insert($property);
                    //插入变体图片
                    if (isset($data["imgid"][$key]) && isset($data["btimg" . $data["imgid"][$key]]) && checkArr($data["btimg" . $data["imgid"][$key]])) {
                        $btimg = $data["btimg" . $data["imgid"][$key]];
                        $propertyImg = [];
                        if (checkArr($btimg)) {
                            foreach ($btimg as $k => $v) {
                                $px = isset($data['bpx' . $data["imgid"][$key]][$k]) ? $data['bpx' . $data["imgid"][$key]][$k] : 0;
                                $resource_id = $this->insertResource($data['bname' . $data["imgid"][$key]][$k], $v, $data['bsize' . $data["imgid"][$key]][$k], $data['bpostfix' . $data["imgid"][$key]][$k], $data['boriginal' . $data["imgid"][$key]][$k], $newResourceTbale);
                                $propertyImg[] = ['resource_id' => $resource_id, 'guid' => $guid, 'px' => $px, 'serial' => $m, 'lang' => $lang, 'updatetime' => date("Y-m-d H:i:s", time())];
                            }
                            count($propertyImg) > 0 && Db::name($newProductImgTbale)->insertAll($propertyImg);
                        }
                    }
                }
            }
        }

        //更改容量信息
        if (isession('type') == 2) {
            $sql = "UPDATE ean_company SET use_capacity = (use_capacity+" . $num . ") WHERE id=" . $company_id;
            $this->pdo->query($sql);
        }
        return ['status' => true];
    }

    /**
     * 产品新增、编辑提交检测
     * @param array $where
     * @param string $newProductTable
     * @return int
     * @throws \think\Exception
     */
    public function repeateProduct($where = [], $newProductTable = '')
    {
        $num = DB::name($newProductTable)->where($where)->count();
        if ($num > 0) {
            return 1;
        }
        return 2;
    }

    /**
     * 插入资源数据
     * @param string $name
     * @param string $path
     * @param string $size
     * @param string $postfix
     * @param string $original
     * @param string $table
     * @param string $module
     * @param int $status
     * @return string
     */
    public function insertResource($name = '', $path = '', $size = '', $postfix = '', $original = '', $table = '', $module = 'product', $status = 1)
    {
        if (empty($table)) {
            //资源表
            $resourceTbale = "resource";
            $table = $resourceTbale . "_" . isession('company_id');
            if ($this->checkTableExist($table) == false) {
                $this->copyTable($resourceTbale, $table, isession('company_id'));
            }
        }
        $insertData['module'] = $module;
        $insertData['name'] = $name;
        $insertData['path'] = $path;
        $insertData['size'] = $size;
        $insertData['postfix'] = $postfix;
        $insertData['original'] = $original;
        $insertData['timestamp'] = time();
        $insertData['status'] = $status;
        $insertData['user_id'] = isession('user_id');
        DB::name($table)->insert($insertData);
        return Db::name($table)->getLastInsID();
    }

    /**
     * 删除产品信息
     * @param array $data
     * @param string $company_id
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function productDel($data = [], $company_id = '')
    {
        //产品表
        $productTbale = 'products';
        $newProductTable = $data['lang'] ? $productTbale . "_" . $data['lang'] . "_" . $company_id : $productTbale . "_" . $company_id;
        //产品图表
        $productImgTbale = 'img';
        $newProductImgTbale = $productImgTbale . "_" . $company_id;
        //属性表
        $propertyTbale = 'shuxing';
        $newPropertyTbale = $propertyTbale . "_" . $company_id;
        //资源表
        $resourceTbale = "resource";
        $newResourceTbale = $resourceTbale . "_" . $company_id;

        if (checkArr($data['guid'])) {
            $where['guid'] = ['in', $data['guid']];
        } else {
            $where['guid'] = $data['guid'];
        }
        //公司分表存在删除数据
        if ($this->checkTableExist($newProductTable)) {
            Db::name($newProductTable)->where($where)->delete();
        }
        $where['lang'] = $data['lang'] ? $data['lang'] : "moren";
        if ($this->checkTableExist($newProductImgTbale)) {
            //获取产品下图片资源id
            $resource = Db::name($newProductImgTbale)->field('resource_id')->where($where)->select();
            $resource_id = checkArr($resource) ? array_column($resource, 'resource_id') : [];
            //删除图片信息
            Db::name($newProductImgTbale)->where($where)->delete();
            //删除资源库数据
//            if ($this->checkTableExist($newResourceTbale) && checkArr($resource_id)) {
//                //资源id是否在图片中还存在
//                $resources = Db::name($newProductImgTbale)->field('resource_id')->where(['resource_id' => ['in', $resource_id]])->select();
//                //删除资源库数据
//                $resource_ids = array_diff($resource_id, array_column($resources, 'resource_id'));
//                checkArr($resource_ids) && Db::name($newResourceTbale)->where(['id' => ['in', $resource_ids]])->delete();
//            }
        }
        if ($this->checkTableExist($newPropertyTbale)) {
            Db::name($newPropertyTbale)->where($where)->delete();
        }

        return true;
    }

    /**
     * 更新审核状态
     * @param array $where
     * @param string $lang
     * @param int $type
     * @param string $company_id
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function updateAudit($where = [], $lang = '', $type = 1, $company_id = '')
    {
        //产品表
        $productTbale = 'products';
        $newProductTable = $lang ? $productTbale . "_" . $lang . "_" . $company_id : $productTbale . "_" . $company_id;

        //公司分表不存在
        if ($this->checkTableExist($newProductTable) == false) {
            return false;
        }
        Db::name($newProductTable)
            ->where($where)
            ->update(['audit' => $type]);

        return true;
    }

    /**
     * 根据产品id更新产品主表信息
     * @param string $id
     * @param array $updateData
     * @param string $lang
     * @param string $company_id
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function updateProduct($id = '', $updateData = [], $lang = '', $company_id = '')
    {
        //产品表
        $productTbale = 'products';
        $newProductTable = $lang ? $productTbale . "_" . $lang . "_" . $company_id : $productTbale . "_" . $company_id;

        //公司分表不存在
        if ($this->checkTableExist($newProductTable) == false) {
            return false;
        }
        Db::name($newProductTable)
            ->where('id', $id)
            ->update($updateData);

        return true;
    }

    /**
     *  更新产品主表信息
     * @param array $where
     * @param array $updateData
     * @param string $lang
     * @param string $company_id
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function updateProductByWhere($where = [], $updateData = [], $lang = '', $company_id = '')
    {
        //产品表
        $productTbale = 'products';
        $newProductTable = $lang ? $productTbale . "_" . $lang . "_" . $company_id : $productTbale . "_" . $company_id;

        //公司分表不存在
        if ($this->checkTableExist($newProductTable) == false) {
            return false;
        }
        Db::name($newProductTable)
            ->where($where)
            ->update($updateData);
        return true;
    }

    /**
     * 获取分类下的产品数量   products+$company_id+$lang
     * @param array $data
     * @param string $lang
     * @param string $company_id
     * @return int|string
     * @throws \think\Exception
     */
    public function productNum($data = [], $lang = '', $company_id = '')
    {
        //产品表
        $productTbale = 'products';
        $newProductTable = $lang ? $productTbale . "_" . $lang . "_" . $company_id : $productTbale . "_" . $company_id;

        if ($this->checkTableExist($newProductTable) == false) {
            return 0;
        }
        //获取分类商品数量
        $where['bname'] = $data['bname'];
        $where['user_name'] = $data['user_name'];
        $where['platform'] = $data['platform'];
        return Db::name($newProductTable)->where($where)->count();
    }

    /**
     * 删除分类下的产品信息
     * @param array $data
     * @param string $lang
     * @param string $company_id
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function delCategory($data = [], $lang = '', $company_id = '')
    {
        //产品表
        $productTbale = 'products';
        $newProductTable = $lang ? $productTbale . "_" . $lang . "_" . $company_id : $productTbale . "_" . $company_id;
        //产品图表
        $productImgTbale = 'img';
        $newProductImgTbale = $productImgTbale . "_" . $company_id;
        //属性表
        $propertyTbale = 'shuxing';
        $newPropertyTbale = $propertyTbale . "_" . $company_id;
        //资源表
        $resourceTbale = "resource";
        $newResourceTbale = $resourceTbale . "_" . $company_id;

        //产品表不存在，直接返回
        if ($this->checkTableExist($newProductTable) == false) {
            return false;
        }

        //获取分类下所有产品的guid
        $where['bname'] = $data['bname'];
        $where['platform'] = $data['platform'];
        $where['user_name'] = $data['user_name'];
        $guids = Db::name($newProductTable)->field('guid')->Where($where)->select();

        //没有产品信息
        if (!checkArr($guids)) {
            return false;
        }

        $nwhere['guid'] = ['in', array_column($guids, 'guid')];
        Db::name($newProductTable)->where($nwhere)->delete();
        $nwhere['lang'] = $lang ? $lang : 'moren';
        if ($this->checkTableExist($newProductImgTbale)) {
            //获取产品下图片资源id
            $resource = Db::name($newProductImgTbale)->field('resource_id')->where($nwhere)->select();
            $resource_id = checkArr($resource) ? array_column($resource, 'resource_id') : [];
            //删除图片信息
            Db::name($newProductImgTbale)->where($nwhere)->delete();
            //删除资源库数据
//            if ($this->checkTableExist($newResourceTbale) && checkArr($resource_id)) {
//                Db::name($newResourceTbale)->where(['id' => ['in', $resource_id]])->delete();
//            }
        }

        if ($this->checkTableExist($newPropertyTbale)) {
            Db::name($newPropertyTbale)->where($nwhere)->delete();
        }
        return true;
    }

    /**
     * 一键翻译数据
     * @param array $data
     * @param $lang
     * @param array $sessions
     * @param array $dataArr
     * @param $ylang
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function productHandle($data = [], $lang, $sessions = [], $dataArr = [], $ylang)
    {
        //产品表
        $productTbale = 'products';
        $productOldTbale = $ylang ? $productTbale . "_" . $ylang . "_" . $sessions['company_id'] : $productTbale . "_" . $sessions['company_id'];
        $newProductTable = $productTbale . "_" . $lang . "_" . $sessions['company_id'];
        //产品图表
        $productImgTbale = 'img';
        $newProductImgTbale = $productImgTbale . "_" . $sessions['company_id'];
        //属性表
        $propertyTbale = 'shuxing';
        $newPropertyTbale = $propertyTbale . "_" . $sessions['company_id'];

        //公司分表不存在
        if ($this->checkTableExist($productOldTbale) == false) {
            return false;
        }
        if ($this->checkTableExist($newProductTable) == false) {
            $this->copyTable($productTbale, $newProductTable, $sessions['company_id']);
        }
        if ($this->checkTableExist($newProductImgTbale) == false) {
            $this->copyTable($productImgTbale, $newProductImgTbale, $sessions['company_id']);
        }
        if ($this->checkTableExist($newPropertyTbale) == false) {
            $this->copyTable($propertyTbale, $newPropertyTbale, $sessions['company_id']);
        }
        //检测当前产品在语言表中是否存在
        $res = Db::name($newProductTable)->where('guid', $data['guid'])->count('id');

        $ylang = $ylang ? $ylang : 'moren';
        if ($res == 0) {//不存在，新建数据
            //新建主数据
            $insertData = array(
                'source' => $data['source'],
                'proname' => $dataArr['proname'],
                'tmd5' => md5($dataArr['proname']),
                'sketch' => $dataArr['sketch'],
                'keywords' => $dataArr['keywords'],
                'content' => $dataArr['content'],
                'user_name' => $sessions['username'],
                'ndate' => date("Y-m-d", time()),
                'audit' => 2,
                'guid' => $data['guid'],
                'title' => $data['title'],
                'skucode' => $data['skucode'],
                'price' => $data['price'],
                'saleprice' => $data['saleprice'],
                'coin' => $data['coin'],
                'code' => $data['code'],
                'kucun' => $data['kucun'],
                'weight' => $data['weight'],
                'btname' => $data['btname'],
                'bname' => $data['bname'],
                'platform' => $data['platform']
            );
            $rwhere['tmd5'] = $insertData['tmd5'];
            $insertData['repeat'] = $this->repeateProduct($rwhere, $newProductTable);
            DB::name($newProductTable)->insert($insertData);
//            $sql = "insert into " . $this->getConfig('prefix') . $newProductTable . "(isshare,audit,source,proname,sketch,keywords,content,user_name,ndate,guid,title,skucode,price,saleprice,coin,code,kucun,weight,btname,bname,platform) select isshare,audit,source,'" . $dataArr["proname"] . "','" . $dataArr["sketch"] . "','" . $dataArr["keywords"] . "','" . $dataArr["content"] . "','" . $sessions['username'] . "','" . date("Y-m-d", time()) . "',guid,title,skucode,price,saleprice,coin,code,kucun,weight,btname,bname,platform from " . $this->getConfig('prefix') . $productOldTbale . " where guid='" . $data["guid"] . "'";
//            $this->pdo->exec($sql);

            //新建变体数据
            //检测是否存在变体
            $where = ['guid' => $data["guid"], 'lang' => $ylang];
            $bt = Db::name($newPropertyTbale)->where($where)->count('guid');
            if ($bt != 0) {
                $sql1 = "insert into " . $this->getConfig('prefix') . $newPropertyTbale . "(btname_id,lang,serial,cname,price,saleprice,kucun,skucode,weight,carriage,cost,guid) select btname_id,'" . $lang . "',serial,cname,price,saleprice,kucun,skucode,weight,carriage,cost,guid from  " . $this->getConfig('prefix') . $newPropertyTbale . " where guid='" . $data["guid"] . "' AND lang='" . $ylang . "'";
                $this->pdo->exec($sql1);
            }

            //新建图片数据
            //检测产品图片是否存在
            $img = Db::name($newProductImgTbale)->where($where)->count('guid');
            if ($img != 0) {
                $sql2 = "insert into " . $this->getConfig('prefix') . $newProductImgTbale . "(lang,resource_id,guid,serial,px) select '" . $lang . "',resource_id,guid,serial,px from  " . $this->getConfig('prefix') . $newProductImgTbale . " where guid='" . $data["guid"] . "' AND lang='" . $ylang . "'";
                $this->pdo->exec($sql2);
            }
        } else {//更新数据
            $insertData['proname'] = $dataArr["proname"];
            $insertData['content'] = $dataArr["content"];
            $insertData['sketch'] = $dataArr["sketch"];
            $insertData['keywords'] = $dataArr["keywords"];
            Db::name($newProductTable)->where('guid', $data["guid"])->update($insertData);
        }
        return true;
    }

    /**
     * 根据sku获取主表中的商品信息
     * @param string $sku
     * @param string $company_id
     * @return array|false|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getGoodBySku($sku = '', $company_id = '')
    {
        //产品表
        $productTbale = "products_" . $company_id;
        if ($this->checkTableExist($productTbale) == false) {//公司分表不存在
            return [];
        }
        //主要数据
        $data = Db::name($productTbale)->where('skucode', $sku)->find();
        if (checkArr($data)) {
            return $data;
        }

        //属性表
        $propertyTbale = "shuxing_" . $company_id;
        if ($this->checkTableExist($propertyTbale) == false) {
            return [];
        }
        return Db::name($propertyTbale)->where('skucode', $sku)->find();
    }

    /**
     * 统计商品数量
     * @param string $company_id
     * @param string $where
     * @return int|string
     * @throws \think\Exception
     */
    public function countGood($company_id = '', $where = '')
    {
        //产品表
        $productTbale = "products_" . $company_id;
        if ($this->checkTableExist($productTbale) == false) {//公司分表不存在
            return 0;
        }
        return DB::name($productTbale)->where($where)->count();
    }

    /**
     * 检测产品重复性
     * @param array $data
     * @param string $company_id
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function detectionRepeate($data = [], $company_id = '')
    {
        $company_id = empty($company_id) ? isession('company_id') : $company_id;
        //产品表
        $productTbale = 'products';
        $newProductTable = $data['lang'] ? $productTbale . "_" . $data['lang'] . "_" . $company_id : $productTbale . "_" . $company_id;

        //公司分表不存在
        if ($this->checkTableExist($newProductTable) == false) {
            return $this->returnError('产品信息不存在');
        }
        //查找产品信息
        $product = DB::name($newProductTable)->field('proname,repeat')->where('guid', $data['guid'])->find();
        if (!checkArr($product)) {
            return $this->returnError('产品信息不存在');
        }

        $tmd5 = md5($product['proname']);
        $where['tmd5'] = $tmd5;
        $where['user_name'] = ssession('username');
        $where['guid'] = ['neq', $data['guid']];
        $num = DB::name($newProductTable)->where($where)->count();
        if ($num == 0 && $product['repeat'] == 2) {
            return $this->returnCorrect('当前产品暂未重复');
        }
        if ($num > 0 && $product['repeat'] == 1) {
            return $this->returnCorrect('当前产品标题重复');
        }
        if ($num == 0 && $product['repeat'] == 1) {
            $update['repeat'] = 2;
            $res = $this->returnCorrect('当前产品暂未重复');
        }
        if ($num > 0 && $product['repeat'] == 2) {
            $update['repeat'] = 1;
            $res = $this->returnCorrect('当前产品标题重复');
        }
        DB::name($newProductTable)->where('guid', $data['guid'])->update($update);
        return $res;
    }

    /**************************************导入cvs************************************************/

    /**
     * 检测主产品是否存在
     * @param string $skucode
     * @param string $company_id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function checkMainProduct($skucode = '', $company_id = '')
    {

        $company_id = empty($company_id) ? isession('company_id') : $company_id;
        $productTbale = 'products' . "_" . $company_id;
        if ($this->checkTableExist($productTbale) == false) {
            return false;
        }

        $res = DB::name($productTbale)->where('skucode', $skucode)->find();
        return checkArr($res);
    }

    /**
     * url 插入资源数据
     * @param string $url
     * @param string $module
     * @param int $status
     * @return string
     */
    public function insertResourceByUrl($url = '', $module = 'product', $status = 1)
    {
        //资源表
        $resourceTbale = "resource";
        $table = $resourceTbale . "_" . isession('company_id');
        if ($this->checkTableExist($table) == false) {
            $this->copyTable($resourceTbale, $table, isession('company_id'));
        }

        $path = trim($url);
        $msg = explode('/', $path);
        $i = count($msg);
        $name = $msg[$i - 1];
        $postfix = explode('.', $name);

        $insertData['module'] = $module;
        $insertData['name'] = $name;
        $insertData['path'] = $path;
        $insertData['size'] = 0;
        $insertData['postfix'] = end($postfix);
        $insertData['original'] = $name;
        $insertData['timestamp'] = time();
        $insertData['status'] = $status;
        $insertData['user_id'] = isession('user_id');
        DB::name($table)->insert($insertData);
        return Db::name($table)->getLastInsID();
    }

    /**
     * 上传产品
     * @param $insertData
     * @param string $company_id
     * @return string
     */
    public function insertProduct($insertData, $company_id = '')
    {
        $company_id = empty($company_id) ? isession('company_id') : $company_id;
        //产品表
        $productTbale = 'products';
        $newProductTable = $productTbale . "_" . $company_id;
        //公司分表不存在
        if ($this->checkTableExist($newProductTable) == false) {
            $this->copyTable($productTbale, $newProductTable, $company_id);
        }

        DB::name($newProductTable)->insert($insertData);
        return Db::name($newProductTable)->getLastInsID();
    }

    /**
     * 上传变体
     * @param $insertData
     * @param string $company_id
     * @param string $type
     */
    public function insertProperty($insertData, $type = '', $company_id = '')
    {
        $company_id = empty($company_id) ? isession('company_id') : $company_id;
        //属性表
        $propertyTbale = 'shuxing';
        $newPropertyTbale = $propertyTbale . "_" . $company_id;
        if ($this->checkTableExist($newPropertyTbale) == false) {
            $this->copyTable($propertyTbale, $newPropertyTbale, $company_id);
        }

        if ($type == 'all') {
            DB::name($newPropertyTbale)->insertAll($insertData);
        } else {
            DB::name($newPropertyTbale)->insert($insertData);
        }
    }

    /**
     * 上传产品图
     * @param $insertData
     * @param string $company_id
     * @param string $type
     */
    public function insertImg($insertData, $type = '', $company_id = '')
    {
        $company_id = empty($company_id) ? isession('company_id') : $company_id;
        //产品图表
        $productImgTbale = 'img';
        $newProductImgTbale = $productImgTbale . "_" . $company_id;
        if ($this->checkTableExist($newProductImgTbale) == false) {
            $this->copyTable($productImgTbale, $newProductImgTbale, $company_id);
        }
        if ($type == 'all') {
            DB::name($newProductImgTbale)->insertAll($insertData);
        } else {
            DB::name($newProductImgTbale)->insert($insertData);
        }
    }

    /***************************************** 导出excel **************************************************/

    /**
     * 获取产品列表
     * @param array $data
     * @param string $company_id
     * @param string $where
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getProductList($data = [], $company_id = 0, $where = [])
    {
        //产品表
        $productTbale = 'products';
        $lang = isset($data['lang']) ? $data['lang'] : '';
        $newProductTable = !empty($lang) ? $productTbale . "_" . $lang . "_" . $company_id : $productTbale . "_" . $company_id;
        //公司分表不存在
        if ($this->checkTableExist($newProductTable) == false) {
            return [];
        }
        $guids = isset($data['guids']) ? $data['guids'] : '';
        $source = isset($data['source']) ? $data['source'] : '';

        $proname = isset($data['proname']) ? $data['proname'] : '';
        $code = isset($data['code']) ? $data['code'] : '';
        $platformStr = isset($data['platform']) ? $data['platform'] : '';
        $audit = isset($data['audit']) ? $data['audit'] : '';
        $bname = isset($data['bname']) ? $data['bname'] : '';//分类
        $user_name = isset($data['user_name']) ? $data['user_name'] : '';
        $user_name = $user_name ? $user_name : ssession('username');
        $start = isset($data['start']) ? $data['start'] : '';
        $end = isset($data['end']) ? $data['end'] : '';

        !empty($audit) && $where['audit'] = $audit;
        !empty($start) && $where['ndate'] = ['>=', $start];
        !empty($end) && $where['ndate'] = ['<=', $end];
        if ($guids) {
            $where['guid'] = ['in', explode(',', $guids)];
        } else {
            !empty($code) && $where['skucode'] = ['like', '%' . $code . '%'];
            !empty($proname) && $where['proname'] = ['like', '%' . $proname . '%'];
            !empty($platformStr) && $where['platform'] = $platformStr;
            !empty($bname) && $where['bname'] = $bname;
        }
        !empty($source) && $where['source'] = $source;

        //判断是否是管理员
        !checkAdministrator() && $where['user_name'] = $user_name;

        $dataArr = Db::name($newProductTable)
            ->where($where)
            ->order('id desc')
            ->select();

        return $dataArr;
    }

    /**
     * 获取某个对应产品图片
     * @param string $guid
     * @param string $lang
     * @param int $serial
     * @param string $company_id
     * @return array|false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getOneProductImg($guid = '', $lang = '', $serial = 0, $company_id = '')
    {
        //产品图表
        $productImgTbale = 'img_' . $company_id;
        if ($this->checkTableExist($productImgTbale) == false) {
            return [];
        }

        //资源表
        $resourceTbale = "resource_" . $company_id;
        if ($this->checkTableExist($resourceTbale) == false) {
            return [];
        }

        $guid && $where['guid'] = $guid;
        $where['lang'] = $lang ? $lang : 'moren';
        $where['serial'] = $serial;
        $imgs = Db::name($productImgTbale)
            ->where($where)
            ->alias('p')
            ->join($resourceTbale . ' r', 'p.resource_id = r.id')
            ->where('r.status=1')
            ->field("r.path")
            ->order('p.px asc')
            ->select();
        return $imgs;
    }

    /**
     * 获取变体信息
     * @param string $guid
     * @param string $lang
     * @param string $company_id
     * @return array|false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getPriductShuxing($guid = '', $lang = '', $company_id = '')
    {
        $propertyTbale = "shuxing_" . $company_id;

        if ($this->checkTableExist($propertyTbale) == false) {
            return [];
        }
        $where['guid'] = $guid;
        $where['lang'] = $lang ? $lang : 'moren';
        return Db::name($propertyTbale)->where($where)->order('serial asc')->select();
    }

    /******************************* 分享 ********************************/

    /**
     * 新建分享数据
     * @param array $data
     * @param string $company_id
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function insertShare($data = [], $company_id = '')
    {

        $lang = isset($data['lang']) ? $data['lang'] : '';
        //产品表
        $productTbale = 'products';
        $newProductTable = $lang ? $productTbale . "_" . $lang . "_" . $company_id : $productTbale . "_" . $company_id;
        //产品图表
        $productImgTbale = 'img';
        $newProductImgTbale = $productImgTbale . "_" . $company_id;
        //属性表
        $propertyTbale = 'shuxing';
        $newPropertyTbale = $propertyTbale . "_" . $company_id;
        //资源表
        $resourceTbale = "resource";
        $newResourceTbale = $resourceTbale . "_" . $company_id;

        //公司分表不存在
        if ($this->checkTableExist($newProductTable) == false) {
            return $this->errorReturn('当前数据不存在');
        }
        if ($this->checkTableExist($newProductImgTbale) == false) {
            return $this->errorReturn('当前数据不存在');
        }
        if ($this->checkTableExist($newPropertyTbale) == false) {
            return $this->errorReturn('当前数据不存在');
        }
        if ($this->checkTableExist($newResourceTbale) == false) {
            return $this->errorReturn('当前数据不存在');
        }

        //检测当前产品在语言表中是否存在
        $product = Db::name($newProductTable)->where('id', $data['id'])->find();
        if (!checkArr($product)) {//不存在
            return $this->errorReturn('当前数据不存在');
        }

        empty($lang) && $lang = 'moren';
        //检测是否已经分享过
        $where['guid'] = $product['guid'];
        $where['lang'] = $lang;
        $where['share'] = $data['type'];
        $where['user_id'] = isession('user_id');
        $res = Db::name('products_share')->where($where)->find();
        if (checkArr($res)) {//存在
            return $this->errorReturn('当前数据已经分享过');
        }

        //创建分类信息
        $category = Db::name('bcategory')->where('id', $product['bcate_id'])->find();

        //新建主数据
        $insert = array(
            'proname' => $product['proname'],
            'price' => $product['price'],
            'saleprice' => $product['saleprice'],
            'coin' => $product['coin'],
            'code' => $product['code'],
            'content' => $product['content'],
            'ndate' => $product['ndate'],
            'skucode' => $product['skucode'],
            'lang' => $lang,
            'weight' => $product['weight'],
            'keywords' => $product['keywords'],
            'des' => $product['des'],
            'kucun' => $product['kucun'],
            'btname' => $product['btname'],
            'fromurl' => $product['fromurl'],
            'platform' => $product['platform'],
            'shopname' => $product['shopname'],
            'sketch' => $product['sketch'],
            'title' => $product['title'],
            'carriage' => $product['carriage'],
            'cost' => $product['cost'],
            'guid' => $product['guid'],
            'timestamp' => time(),
            'brand' => $product['brand'],
            'origin' => $product['origin'],
            'facturer' => $product['facturer'],
            'number' => $product['number'],
            'department' => $product['department'],
            'material' => $product['material'],
            'metal' => $product['metal'],
            'gem' => $product['gem'],
            'package' => $product['package'],
            'hscode' => $product['hscode'],
            'english' => $product['english'],
            'chinese' => $product['chinese'],
            'user_id' => isession('user_id'),
            'truename' => session('truename'),
            'share' => $data['type'],
            'company_id' => $company_id,
            'catename' => $category['bname'],
            'zycategory' => $category['zycategory']
        );
        Db::name('products_share')->insert($insert);
        $pid = Db::name('products_share')->getLastInsID();

        //新建变体数据
        //检测是否存在变体
        $bt = Db::name($newPropertyTbale)->where("guid='" . $product['guid'] . "' AND lang='" . $lang . "'")->select();
        if (checkArr($bt)) {
            foreach ($bt as $value) {
                $binsert[] = array(
                    'serial' => $value['serial'],
                    'cname' => $value['cname'],
                    'btname_id' => $value['btname_id'],
                    'price' => $value['price'],
                    'saleprice' => $value['saleprice'],
                    'kucun' => $value['kucun'],
                    'skucode' => $value['skucode'],
                    'weight' => $value['weight'],
                    'carriage' => $value['carriage'],
                    'cost' => $value['cost'],
                    'lang' => $lang,
                    'guid' => $product['guid'],
                    'updatetime' => $value['updatetime'],
                    'pid' => $pid
                );
            }
            Db::name('shuxing_share')->insertAll($binsert);
        }

        //新建图片数据
        //检测产品图片是否存在
        $imgs = Db::name($newProductImgTbale)->where("guid='" . $product['guid'] . "' AND lang='" . $lang . "'")->select();
        if (checkArr($imgs)) {
            $resource_ids = array_unique(array_column($imgs, 'resource_id'));
            $resource = [];
            if (checkArr($resource_ids)) {
                //查找资源信息,新建资源信息
                $rwhere['id'] = ['in', join(',', $resource_ids)];
                $rwhere['status'] = 1;
                $resources = Db::name($newResourceTbale)->where($rwhere)->select();
                if (checkArr($resources)) {
                    foreach ($resources as $value) {
                        $rinsert = array(
                            'module' => $value['module'],
                            'name' => $value['name'],
                            'path' => $value['path'],
                            'size' => $value['size'],
                            'postfix' => $value['postfix'],
                            'original' => $value['original'],
                            'user_id' => $value['user_id'],
                            'pid' => $pid
                        );
                        Db::name('resource_share')->insert($rinsert);
                        $resource[$value['id']] = Db::name('resource_share')->getLastInsID();
                    }
                }
            }

            //添加图片信息
            foreach ($imgs as $value) {
                $iinsert[] = array(
                    'guid' => $value['guid'],
                    'serial' => $value['serial'],
                    'px' => $value['px'],
                    'lang' => $lang,
                    'resource_id' => isset($resource[$value['resource_id']]) ? $resource[$value['resource_id']] : '',
                    'pid' => $pid
                );
            }
            Db::name('img_share')->insertAll($iinsert);
        }
        return $this->errorReturn('分享成功', true);
    }

    /**
     * 导入分享数据到个人产品库
     * @param string $id
     * @param string $company_id
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function uploadShareToOwn($id = '', $company_id = '')
    {
        if ($id == '') {
            return $this->errorReturn('当前数据不存在');
        }
        //获取主产品信息
        $product = DB::name('products_share')->where('id', $id)->find();
        if (!checkArr($product)) {
            return $this->errorReturn('当前数据不存在');
        }

        //产品表
        $productTbale = 'products';
        $newProductTable = $productTbale . "_" . $company_id;

        //产品图表
        $productImgTbale = 'img';
        $newProductImgTbale = $productImgTbale . "_" . $company_id;
        //属性表
        $propertyTbale = 'shuxing';
        $newPropertyTbale = $propertyTbale . "_" . $company_id;
        //资源表
        $resourceTbale = "resource";
        $newResourceTbale = $resourceTbale . "_" . $company_id;

        //公司分表不存在
        if ($this->checkTableExist($newProductTable) == false) {
            $this->copyTable($productTbale, $newProductTable, $company_id);
        }
        if ($this->checkTableExist($newProductImgTbale) == false) {
            $this->copyTable($productImgTbale, $newProductImgTbale, $company_id);
        }
        if ($this->checkTableExist($newPropertyTbale) == false) {
            $this->copyTable($propertyTbale, $newPropertyTbale, $company_id);
        }
        if ($this->checkTableExist($newResourceTbale) == false) {
            $this->copyTable($resourceTbale, $newResourceTbale, $company_id);
        }

        //加入图片文件没变化到，也就是存在，就不必重复上传了，不存在则上传
        $dir = server('DOCUMENT_ROOT');
        $ftmp_name = '/files/' . isession('user_id') . '/product/' . date("Ymd", time()) . "/";
        if (!is_dir($dir . $ftmp_name)) {
            if (!mkdir($dir . $ftmp_name, 0777, true)) {
                return $this->errorReturn('没有权限创建目录');
            }
        }


        //获取产品分类
        $bwhere['bname'] = $product['catename'];
        $bwhere['user_name'] = ssession('username');
        $bwhere['platform'] = $product['platform'];
        $bwhere['company_id'] = $company_id;
        $res = DB::name('bcategory')->where($bwhere)->find();
        if (checkArr($res)) {
            $bcate_id = $res['id'];
        } else {
            $binsert = array(
                'bname' => $product['catename'],
                'user_name' => ssession('username'),
                'truename' => ssession('truename'),
                'platform' => $product['platform'],
                'company_id' => $company_id,
                'zycategory' => $product['zycategory']
            );
            Db::name('bcategory')->insert($binsert);
            $bcate_id = Db::name('bcategory')->getLastInsID();
        }

        //查找当前产品是否已经导入
        $pwhere['shareguid'] = $product["guid"];
        $pwhere['lang'] = $product["lang"];
        $pwhere['isshare'] = 2;
        $pwhere['user_name'] = ssession('username');
        $res = DB::name($newProductTable)->where($pwhere)->count('id');
        if ($res > 0) {
            return $this->errorReturn('当前产品已经导入，请不要重复导入');
        }

        $guid = create_guid();
        $pinsert = array(
            'guid' => $guid,
            'proname' => $product["proname"],
            'title' => $product["proname"],
            'skucode' => guid(),
            'price' => $product["price"],
            'saleprice' => $product["saleprice"],
            'coin' => $product["coin"],
            'code' => randomkeys(8),
            'carriage' => $product["carriage"],
            'cost' => $product["cost"],
            'kucun' => $product["kucun"],
            'weight' => $product["weight"],
            'fromurl' => $product["fromurl"],
            'btname' => $product["btname"],
            'des' => $product["des"],
            'source' => 2,
            'audit' => 1,
            'keywords' => $product["keywords"],
            'content' => $product["content"],
            'bcate_id' => $bcate_id,
            'bname' => $product['catename'],
            'platform' => $product['platform'],
            'user_name' => ssession('username'),
            'ndate' => $product['ndate'],
            'timestamp' => time(),
            'brand' => $product['brand'],
            'origin' => $product['origin'],
            'facturer' => $product['facturer'],
            'number' => $product['number'],
            'department' => $product['department'],
            'material' => $product['material'],
            'metal' => $product['metal'],
            'gem' => $product['gem'],
            'package' => $product['package'],
            'hscode' => $product['hscode'],
            'english' => $product['english'],
            'chinese' => $product['chinese'],
            'isshare' => 2,
            'lang' => $product["lang"],
            'shareguid' => $product["guid"]
        );
        Db::name($newProductTable)->insert($pinsert);

        //添加变体信息
        $shuxing = DB::name('shuxing_share')->where('pid', $id)->order('serial asc')->select();
        if (checkArr($shuxing)) {
            foreach ($shuxing as $value) {
                $binsert[] = array(
                    'serial' => $value['serial'],
                    'cname' => $value['cname'],
                    'btname_id' => $value['btname_id'],
                    'price' => $value['price'],
                    'saleprice' => $value['saleprice'],
                    'kucun' => $value['kucun'],
                    'skucode' => $value['skucode'],
                    'weight' => $value['weight'],
                    'carriage' => $value['carriage'],
                    'cost' => $value['cost'],
                    'lang' => 'moren',
                    'guid' => $guid,
                    'updatetime' => $value['updatetime']
                );
            }
            Db::name($newPropertyTbale)->insertAll($binsert);
        }

        checkArr($shuxing) && $shuxing = arrayCombine($shuxing, 'serial');
        //获取资源信息
        $resource = DB::name('resource_share')->where('pid', $id)->select();
        checkArr($resource) && $resource = arrayCombine($resource, 'id');

        //获取图片信息
        $imgs = DB::name('img_share')->where('pid', $id)->select();
        if (checkArr($imgs)) {
            $resource_ids = array_unique(array_column($imgs, 'resource_id'));
            $resource = [];
            if (checkArr($resource_ids)) {
                //查找资源信息,新建资源信息
                $resources = DB::name('resource_share')->where('pid', $id)->select();
                if (checkArr($resources)) {
                    $sizes = 0;
                    foreach ($resources as $value) {
                        $sources = $this->copyImg($value['path'], $value['name'], $ftmp_name, $dir);
                        $sources['size'] == true && $sizes += $value['size'];
                        $rinsert = array(
                            'module' => $value['module'],
                            'name' => $value['name'],
                            'path' => $sources['path'],
                            'size' => $value['size'],
                            'postfix' => $value['postfix'],
                            'original' => $value['original'],
                            'timestamp' => time(),
                            'status' => 1,
                            'user_id' => isession('user_id')
                        );
                        Db::name($newResourceTbale)->insert($rinsert);
                        $resource[$value['id']] = Db::name($newResourceTbale)->getLastInsID();
                    }
                    //修改上传空间
                    if (isession('type') == 2 && $sizes > 0) {
                        $sql = "UPDATE ean_company SET use_capacity = (use_capacity+" . $sizes . ") WHERE id=" . $company_id;
                        $this->pdo->query($sql);
                    }
                }
            }

            //添加图片信息
            foreach ($imgs as $value) {
                $iinsert[] = array(
                    'guid' => $guid,
                    'serial' => $value['serial'],
                    'px' => $value['px'],
                    'lang' => 'moren',
                    'resource_id' => isset($resource[$value['resource_id']]) ? $resource[$value['resource_id']] : ''
                );
            }
            Db::name($newProductImgTbale)->insertAll($iinsert);
        }
        return $this->errorReturn('导入成功', true);

    }

    /**
     * 复制图片到个人
     * @param $path
     * @param $name
     * @param $ftmp_name
     * @param $dir
     * @return array
     */
    private function copyImg($path, $name, $ftmp_name, $dir)
    {
        if (file_exists($dir . $ftmp_name . $name)) {
            return ['path' => $path, 'size' => false];
        } else {
            copy($dir . $path, $dir . $ftmp_name . $name);
            return ['path' => $ftmp_name . $name, 'size' => true];
        }
    }

    /**
     * 错误返回
     * @param string $msg
     * @param array $data
     * @param bool $status
     * @return array
     */
    public function errorReturn($msg = '', $status = false, $data = [])
    {
        return ['status' => $status, 'msg' => $msg, 'data' => $data];
    }

    /**************************************** 批量产品改价 **************************************************/

    /**
     * 批量改产品属性
     * @param array $data
     * @param int $company_id
     * @param string $where
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function changePrice($data = [], $company_id = '', $where = [])
    {
        $company_id = empty($company_id) ? isession('company_id') : $company_id;
        //产品表
        $productTbale = 'products';
        $lang = isset($data['lang']) ? $data['lang'] : '';
        $newProductTable = !empty($lang) ? $productTbale . "_" . $lang . "_" . $company_id : $productTbale . "_" . $company_id;
        //公司分表不存在
        if ($this->checkTableExist($newProductTable) == false) {
            return $this->returnError('当前数据不存在');
        }
        //检测选中修改属性存在修改数据
        $choose = explode(',', $data['choose']);
        //需要修改属性数组
        $change = [];
        foreach ($choose as $value) {
            $res = $this->detection($data[$value]);
            if ($res == true) {
                $change[$value] = $data[$value];
            }
        }

        if (count($change) == 0) {
            return $this->returnError('选中数据指定修改类型中修改数据必须大于0');
        }

        $set = [];
        $bset = [];
        foreach ($change as $key => $value) {
            switch ($key) {
                case 'price':
                    $set[] = $this->setSql('price', $value);
                    break;
                case 'saleprice':
                    $set[] = $this->setSql('saleprice', $value);
                    break;
                case 'cost':
                    $set[] = $this->setSql('cost', $value);
                    break;
                case 'kucun':
                    $set[] = $this->setSql('kucun', $value);
                    break;
                case 'bprice':
                    $bset[] = $this->setSql('price', $value);
                    break;
                case 'bsaleprice':
                    $bset[] = $this->setSql('saleprice', $value);
                    break;
                case 'bcost':
                    $bset[] = $this->setSql('cost', $value);
                    break;
                case 'bkucun':
                    $bset[] = $this->setSql('kucun', $value);
                    break;
                default:
                    break;
            }
        }

        $guids = isset($data['guids']) ? $data['guids'] : '';
        $source = isset($data['source']) ? $data['source'] : '';
        $proname = isset($data['proname']) ? $data['proname'] : '';
        $code = isset($data['code']) ? $data['code'] : '';
        $platformStr = isset($data['platform']) ? $data['platform'] : '';
        $audit = isset($data['audit']) ? $data['audit'] : '';
        $bname = isset($data['bname']) ? $data['bname'] : '';//分类
        $user_name = isset($data['user_name']) ? $data['user_name'] : '';
        $user_name = $user_name ? $user_name : ssession('username');
        $start = isset($data['start']) ? $data['start'] : '';
        $end = isset($data['end']) ? $data['end'] : '';

        //判断是否是管理员
        $where['user_name'] = $user_name;
        !empty($source) && $where['source'] = $source;
        !empty($audit) && $where['audit'] = $audit;
        !empty($start) && $where['ndate'] = ['>=', $start];
        !empty($end) && $where['ndate'] = ['<=', $end];
        if ($guids) {
            $where['guid'] = ['in', explode(',', $guids)];
        } else {
            !empty($code) && $where['skucode'] = ['like', '%' . $code . '%'];
            !empty($proname) && $where['proname'] = ['like', '%' . $proname . '%'];
            !empty($platformStr) && $where['platform'] = $platformStr;
            !empty($bname) && $where['bname'] = $bname;
        }

        //存在更改主产品信息
        //查找符合条件产品guid
        $products = DB::name($newProductTable)->field('guid')->where($where)->select();
        $guid = checkArr($products) ? array_column($products, 'guid') : [];
        if (!checkArr($guid)) {
            return $this->returnCorrect('修改完成！');
        }
        $guid = join("','", $guid);

        if (checkArr($set)) {
            $table = $this->getConfig('prefix') . $newProductTable;
            $sql = "UPDATE " . $table . " SET " . join(',', $set) . " WHERE guid in ('" . $guid . "')";
            $this->pdo->query($sql);
        }

        //处理变体信息
        $propertyTbale = 'shuxing';
        $newPropertyTbale = $propertyTbale . "_" . $company_id;
        if ($this->checkTableExist($newPropertyTbale) == false) {
            return $this->returnCorrect('修改完成！');
        }

        //存在修改变体信息
        if (!checkArr($bset)) {
            return $this->returnCorrect('修改完成！');
        }

        $table = $this->getConfig('prefix') . $newPropertyTbale;
        $sql = "UPDATE " . $table . " SET " . join(',', $bset) . " WHERE guid in ('" . $guid . "')";
        $this->pdo->query($sql);
        return $this->returnCorrect('修改完成！');
    }

    /**
     * 检测修改属性信息，修改数据是否为0
     * @param array $data
     * @return bool
     */
    public function detection($data = [])
    {
        if ($data['number'] == 1 && (int)$data['num'] == 0) {
            return false;
        }
        if ($data['number'] == 2 && (int)$data['percent'] == 0) {
            return false;
        }
        return true;
    }

    /**
     * 拼接sql
     * @param string $param
     * @param array $data
     * @return string
     */
    public function setSql($param = '', $data = [])
    {
        $num = $data['number'] == 1 ? $data['num'] : $param . '*' . $data['percent'] / 100;
        if ($data['type'] == 1) {
            return $param . '=(' . $param . '+' . $num . ')';
        } else {
            return $param . '= (IF(' . $param . '>' . $num . ', ' . $param . '-' . $num . ', 0))';
        }
    }

    /**
     * 批量同步产品变体信息
     * @param array $data
     * @param string $company_id
     * @param array $where
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function synchPrice($data = [], $company_id = '', $where = [])
    {
        $company_id = empty($company_id) ? isession('company_id') : $company_id;
        //产品表
        $lang = isset($data['lang']) ? $data['lang'] : '';
        $newProductTable = !empty($lang) ? "products_" . $lang . "_" . $company_id : "products_" . $company_id;
        //公司分表不存在
        if ($this->checkTableExist($newProductTable) == false) {
            return $this->returnError('当前数据不存在');
        }
        //处理变体信息
        $newPropertyTbale = "shuxing_" . $company_id;
        if ($this->checkTableExist($newPropertyTbale) == false) {
            return $this->returnCorrect('当前产品变体数据不存在！');
        }

        $guids = isset($data['guids']) ? $data['guids'] : '';
        $source = isset($data['source']) ? $data['source'] : '';
        $proname = isset($data['proname']) ? $data['proname'] : '';
        $code = isset($data['code']) ? $data['code'] : '';
        $platformStr = isset($data['platform']) ? $data['platform'] : '';
        $audit = isset($data['audit']) ? $data['audit'] : '';
        $bname = isset($data['bname']) ? $data['bname'] : '';//分类
        $user_name = isset($data['user_name']) ? $data['user_name'] : '';
        $user_name = $user_name ? $user_name : ssession('username');
        $start = isset($data['start']) ? $data['start'] : '';
        $end = isset($data['end']) ? $data['end'] : '';

        //判断是否是管理员
        $where['user_name'] = $user_name;
        !empty($source) && $where['source'] = $source;
        !empty($audit) && $where['audit'] = $audit;
        !empty($start) && $where['ndate'] = ['>=', $start];
        !empty($end) && $where['ndate'] = ['<=', $end];
        if ($guids) {
            $where['guid'] = ['in', explode(',', $guids)];
        } else {
            !empty($code) && $where['skucode'] = ['like', '%' . $code . '%'];
            !empty($proname) && $where['proname'] = ['like', '%' . $proname . '%'];
            !empty($platformStr) && $where['platform'] = $platformStr;
            !empty($bname) && $where['bname'] = $bname;
        }
        //查找符合条件产品guid
        $products = DB::name($newProductTable)->field('guid')->where($where)->select();
        $guid = checkArr($products) ? array_column($products, 'guid') : [];
        if (!checkArr($guid)) {
            return $this->returnCorrect('修改完成！');
        }
        $guid = join("','", $guid);

        //检测选中修改属性存在修改数据
        $choose = explode(',', $data['choose']);
        $set = [];
        foreach ($choose as $value) {
            switch ($value) {
                case 'price':
                    $set[] = 's.price = p.price';
                    break;
                case 'saleprice':
                    $set[] = 's.saleprice = p.saleprice';
                    break;
                case 'cost':
                    $set[] = 's.cost = p.cost';
                    break;
                case 'kucun':
                    $set[] = 's.kucun = p.kucun';
                    break;
                default:
                    break;
            }
        }

        $propertyTbale = $this->getConfig('prefix') . $newPropertyTbale;
        $productTbale = $this->getConfig('prefix') . $newProductTable;
        $sql = "UPDATE " . $propertyTbale . " s LEFT JOIN " . $productTbale . " p on s.guid = p.guid SET " . join(',', $set) . "  WHERE " . "s.guid in ('" . $guid . "')";
        $this->pdo->query($sql);
        return $this->returnCorrect('同步完成！');
    }

    /******************************* 错误返回 ********************************/
    /**
     * 错误返回
     * @param string $msg
     * @param array $data
     * @param bool $status
     * @return array
     */
    public function returnError($msg = '', $status = false, $data = [])
    {
        return ['status' => $status, 'msg' => $msg, 'data' => $data];
    }

    /**
     * 正确返回
     * @param string $msg
     * @param array $data
     * @param bool $status
     * @return array
     */
    public function returnCorrect($msg = '', $status = true, $data = [])
    {
        return ['status' => $status, 'msg' => $msg, 'data' => $data];
    }

    /******************************* 批量处理数据库表字段 ********************************/
    /**
     * 批量添加产品字段
     * @return bool
     */
    public function batchProductsTable()
    {
        //添加字段
        $add = 'fanyi';
//        $add = 'upc';
        $sql = "SELECT TABLE_NAME AS tname FROM `INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_SCHEMA`='" . $this->dbName . "' AND TABLE_NAME !='ean_products_share' AND TABLE_NAME LIKE '%ean_products%';";
        $result = $this->pdo->query($sql);
        if (false === $result) {
            return false;
        }
        $tables = $result->fetchAll(PDO::FETCH_ASSOC);
        if (!checkArr($tables)) {
            return false;
        }
        $table = array_column($tables, 'tname');

        foreach ($table as $value) {
//            $sql = "ALTER TABLE `" . $this->dbName . "`.`" . $value . "` MODIFY COLUMN `kucun` int(11) UNSIGNED NOT NULL DEFAULT 0 COMMENT '库存数量',MODIFY COLUMN `carriage` float(11, 2) UNSIGNED NOT NULL DEFAULT 0.00 COMMENT '运费',MODIFY COLUMN `cost` float(11, 2) UNSIGNED NOT NULL DEFAULT 0.00 COMMENT '成本',MODIFY COLUMN `price` float(11, 2) UNSIGNED NOT NULL DEFAULT 0.00 COMMENT '参考价格（float两位）',MODIFY COLUMN `saleprice` float(11, 2) UNSIGNED NOT NULL DEFAULT 0.00 COMMENT '售卖价格（float两位）';";
//            $this->pdo->exec($sql);
            $columns = $this->getColumn($value);
            if (checkArr($columns)) {
                if (!in_array($add, $columns)) {
                    //字段不存在，添加字段
                    $sql = "ALTER TABLE `" . $this->dbName . "`.`" . $value . "` ADD COLUMN `" . $add . "` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '被翻译语言';";
//                    $sql = "ALTER TABLE `" . $this->dbName . "`.`" . $value . "` ADD COLUMN `" . $add . "` tinyint(4) UNSIGNED NOT NULL DEFAULT 2 COMMENT '是否重复产品1是2否';";
//                    $sql = "ALTER TABLE `" . $this->dbName . "`.`" . $value . "` ADD COLUMN `" . $add . "` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '" . $add . "';";
                    $this->pdo->exec($sql);
                }
            }
//            $sql = "UPDATE " . $value . " SET tmd5 = MD5(proname)";
//            $this->pdo->exec($sql);
        }
        return true;
    }

    /**
     * 批量添加变体字段
     * @return bool
     */
    public function batchShuxingTable()
    {
        //添加字段
        $add = 'ean';

        $sql = "SELECT TABLE_NAME AS tname FROM `INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_SCHEMA`='" . $this->dbName . "' AND TABLE_NAME !='ean_shuxing_share' AND TABLE_NAME LIKE '%ean_shuxing%';";
        $result = $this->pdo->query($sql);
        if (false === $result) {
            return false;
        }
        $tables = $result->fetchAll(PDO::FETCH_ASSOC);
        if (!checkArr($tables)) {
            return false;
        }
        $table = array_column($tables, 'tname');

        foreach ($table as $value) {
            $sql = "ALTER TABLE `" . $this->dbName . "`.`" . $value . "`MODIFY COLUMN `cost` float(11, 2) UNSIGNED NOT NULL DEFAULT 0.00 COMMENT '成本',MODIFY COLUMN `price` float(11, 2) UNSIGNED NOT NULL DEFAULT 0.00 COMMENT '参考价格',MODIFY COLUMN `saleprice` float(11, 2) UNSIGNED NOT NULL DEFAULT 0.00 COMMENT '售卖价格';";
            $this->pdo->exec($sql);
//            $columns = $this->getColumn($value);
//            if (checkArr($columns)) {
//                if (!in_array($add, $columns)) {
//                    //字段不存在，添加字段
//                    $sql = "ALTER TABLE `" . $this->dbName . "`.`" . $value . "` ADD COLUMN `" . $add . "` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '" . $add . "';";
//                    $this->pdo->exec($sql);
//                }
//            }
//            $sql = "UPDATE " . $value . " SET tmd5 = MD5(proname)";
//            $this->pdo->exec($sql);
        }
        return true;
    }

    /**
     * 查询指定表所有字段
     * @param string $table
     * @return array
     */
    private function getColumn($table = '')
    {
        $sql = "SELECT column_name FROM `INFORMATION_SCHEMA`.`COLUMNS`  WHERE `TABLE_SCHEMA`='" . $this->dbName . "' and TABLE_NAME='" . $table . "';";
        $result = $this->pdo->query($sql);
        if (false === $result) {
            return [];
        }
        $columns = $result->fetchAll(PDO::FETCH_ASSOC);
        if (!checkArr($columns)) {
            return [];
        }
        return array_column($columns, 'column_name');
    }
}